package com.softeem.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@PropertySource("jdbc.properties")
public class MybatisConfig {
    // Java Config,数据源
    @Bean
    DataSource dataSource(@Value("${jdbc.username}") String username,
                          @Value("${jdbc.password}") String password,
                          @Value("${jdbc.url}") String url,
                          @Value("${jdbc.driver}") String driver){
        HikariConfig config = new HikariConfig();
        config.setUsername(username);
        config.setPassword(password);
        config.setJdbcUrl(url);
        config.setDriverClassName(driver);
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }

    //开启事务前必须要有PlatformTransactionManager对象
    @Bean
    PlatformTransactionManager txManager(@Autowired DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    //mybatis功能核心对象
    // Mybatis: SqlSession session
    // session: Connection Ps
    // 1. JDBC流程自动化
    //  1.1 提交SQL（手动）
    // 2. 结果集--》对象映射自动化
    @Bean
    SqlSessionFactoryBean sqlSessionFactoryBean(@Autowired DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 指定xml映射文件的存放位置，Mybatis会根据该位置加载这些文件
        sqlSessionFactoryBean.setMapperLocations(
                // 表达式转换器
                new PathMatchingResourcePatternResolver()//classpath代表resources目录
                        .getResources("classpath:mapper/*.xml")
        );
        return sqlSessionFactoryBean;
    }

}
